package cn.ppms.controller;

import cn.ppms.pojo.Bill;
import cn.ppms.pojo.Provider;
import cn.ppms.pojo.Role;
import cn.ppms.pojo.User;
import cn.ppms.service.bill.BillService;
import cn.ppms.service.bill.BillServiceImpl;
import cn.ppms.service.provider.ProviderService;
import cn.ppms.service.provider.ProviderServiceImpl;
import cn.ppms.service.role.RoleService;
import cn.ppms.service.role.RoleServiceImpl;
import cn.ppms.tools.Constants;
import cn.ppms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/Bill")
@Controller
public class BillController{

	@RequestMapping("/*")
	protected ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response) throws Exception {
		 

      String method = request.getParameter("method");
		
		System.out.println("mvc+++++method----> " + method);

		if("query".equals(method)){
			return this.query(request,response);
		}else if("add".equals(method)){
			return this.add(request,response);
		}else if("view".equals(method)){
			this.getBillById(request,response,"/jsp/billview.jsp");
		}else if("modify".equals(method)){
			this.getBillById(request,response,"/jsp/billmodify.jsp");
		}else if("modifysave".equals(method)){
			return this.modify(request);
		}else if("delbill".equals(method)){
			this.delBill(request,response);
		}else if("getproviderlist".equals(method)){
			this.getProviderlist(response);
		}

		return null;
	}

	private void getProviderlist(HttpServletResponse response) {
		List<Provider> providerList ;
		ProviderService providerService = new ProviderServiceImpl();
		providerList = providerService.getProviderList("","");
		//把providerList转换成json对象输出
		response.setContentType("application/json");
		PrintWriter outPrintWriter = null;
		try {
			outPrintWriter = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		assert outPrintWriter != null;
		outPrintWriter.write(JSONArray.toJSONString(providerList));
		outPrintWriter.flush();
		outPrintWriter.close();
	}
	private void delBill(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("billid");
		HashMap<String, String> resultMap = new HashMap<>();
		if(id!=null&&!id.isEmpty()){
			BillService billService = new BillServiceImpl();
			boolean flag = billService.deleteBillById(id);
			if(flag){//删除成功
				resultMap.put("delResult", "true");
			}else{//删除失败
				resultMap.put("delResult", "false");
			}
		}else{
			resultMap.put("delResult", "notexit");
		}
		//把resultMap转换成json对象输出
		response.setContentType("application/json");
		PrintWriter outPrintWriter = null;
		try {
			outPrintWriter = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		assert outPrintWriter != null;
		outPrintWriter.write(JSONArray.toJSONString(resultMap));
		outPrintWriter.flush();
		outPrintWriter.close();
	}

	private ModelAndView modify(HttpServletRequest request) {
		String id = request.getParameter("id");
		String productName = request.getParameter("productName");
		String productDesc = request.getParameter("productDesc");
		String productUnit = request.getParameter("productUnit");
		String productCount = request.getParameter("productCount");
		String totalPrice = request.getParameter("totalPrice");
		String providerId = request.getParameter("providerId");
		String isPayment = request.getParameter("isPayment");

		Bill bill = new Bill();
		bill.setId(Integer.valueOf(id));
		bill.setProductName(productName);
		bill.setProductDesc(productDesc);
		bill.setProductUnit(productUnit);
		bill.setProductCount(new BigDecimal(productCount).setScale(2,BigDecimal.ROUND_DOWN));
		bill.setIsPayment(Integer.parseInt(isPayment));
		bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN));
		bill.setProviderId(Integer.parseInt(providerId));

		bill.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
		bill.setModifyDate(new Date());

		BillService billService = new BillServiceImpl();
		if(billService.modify(bill)){
			ModelAndView mv=new ModelAndView("redirect:Bill");
			mv.addObject("method", "query");
			return mv;
		}else{
			return new ModelAndView("billmodify");
		}
	
	}
	
	private void getBillById(HttpServletRequest request, HttpServletResponse response,String url)
			throws ServletException, IOException {
		String id = request.getParameter("billid");
		if(id!=null&&!id.isEmpty()){
			//调用后台方法得到user对象
			BillService billService = new BillServiceImpl();
			Bill bill = null;
			bill = billService.getBillById(id);
			request.setAttribute("bill", bill);
			request.getRequestDispatcher(url).forward(request, response);
		}
		
	}

	private ModelAndView query(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//查询订单列表
		String queryProductName = request.getParameter("queryProductName");
		String queryProviderId = request.getParameter("queryProviderId");
		String queryIsPayment = request.getParameter("queryIsPayment");
		if(queryProductName==null||queryProductName.isEmpty()){
			queryProductName = "";
		}

		BillService billService = new BillServiceImpl();
		List<Bill> billList = null;
		Bill bill = new Bill();

		if(queryIsPayment==null||queryIsPayment.isEmpty()){
			bill.setIsPayment(0);
		}else{
			bill.setIsPayment(Integer.parseInt(queryIsPayment));
		}

		if(queryProviderId==null||queryProviderId.isEmpty()){
			bill.setProviderId(0);
		}else{
			bill.setProviderId(Integer.parseInt(queryProviderId));
		}
		bill.setProductName(queryProductName);
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;

    	if(queryProviderId != null){
    		try{
    			currentPageNo = Integer.parseInt(queryProviderId);
    		}catch(NumberFormatException e){
    			response.sendRedirect("error.jsp");
    		}
    	}	
    	//总数量（表）
		billList = billService.getBillList(bill);
    	int totalCount	= 10;
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	
    	int totalPageCount = pages.getTotalPageCount();
    	
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}

		request.setAttribute("billList", billList);
		List<Role> roleList = null;
		RoleService roleService = new RoleServiceImpl();
		roleList = roleService.getRoleList();

		request.setAttribute("queryProductName", queryProductName);
		request.setAttribute("queryProviderId", queryProviderId);
		request.setAttribute("queryIsPayment", queryIsPayment);

		ProviderService providerService = new ProviderServiceImpl();
		List<Provider> providerList=providerService.getProviderList("","");
		request.setAttribute("providerList", providerList);

		return new ModelAndView("billlist");
	}
	
	private ModelAndView add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String billCode = request.getParameter("billCode");
		String productName = request.getParameter("productName");
		String productDesc = request.getParameter("productDesc");
		String productUnit = request.getParameter("productUnit");
		String productCount = request.getParameter("productCount");
		String totalPrice = request.getParameter("totalPrice");
		String providerId = request.getParameter("providerId");
		String isPayment = request.getParameter("isPayment");

		Bill bill = new Bill();
		bill.setBillCode(billCode);
		bill.setProductName(productName);
		bill.setProductDesc(productDesc);
		bill.setProductUnit(productUnit);
		bill.setProductCount(new BigDecimal(productCount).setScale(2,BigDecimal.ROUND_DOWN));
		bill.setIsPayment(Integer.parseInt(isPayment));
		bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_DOWN));
		bill.setProviderId(Integer.parseInt(providerId));
		bill.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
		bill.setCreationDate(new Date());

		BillService billService = new BillServiceImpl();
		if(billService.add(bill)){
			ModelAndView mv=new ModelAndView("redirect:Bill");
			mv.addObject("method", "query");
			return mv;
		}else{
			return new ModelAndView("billadd");
		}
	}

	
	 
}
